package com.example.smart_home.service;

import com.example.smart_home.mapper.UserMapper;
import com.example.smart_home.pojo.User;
import com.example.smart_home.pojo.UserExample;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserServiceImpl implements UserService {

    //从spring容器中取数据访问层对象
    @Autowired
    UserMapper userMapper;

    @Override
    public User login(User user) {
        //select * from user where name=‘a and password='a'
        //如果查询条件不是主键，必须用example.criteria生成where
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.or();

        criteria.andNameEqualTo(user.getName());
        criteria.andPasswordEqualTo(user.getPassword());

        List<User> list = userMapper.selectByExample(userExample);
        if (list.size() >= 1) {
            //从集合中取出用户信息
            User dbUser = list.get(0);
            return dbUser;
        }
        return null;
    }


    @Override
    public boolean register(User user) {
        boolean isSuccess = false;
        //1判断用户名是否存在
        //select * from user where name='a'
        //where中的条件不是主键，必须要example来生成
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.or();

        criteria.andNameEqualTo(user.getName());
        List<User> list = userMapper.selectByExample(userExample);
        if (list.size() == 0) {
            int insertRow = userMapper.insertSelective(user);
            if (insertRow >= 1) {
                isSuccess = true;
            }

        }


        return isSuccess;
    }

}
